package com.zklh.leetcode.top100;

import java.util.ArrayList;
import java.util.List;

/**
 * 螺旋矩阵算法实现
 *
 * @version 1.0
 * @Author tongnan
 * @Date 2023/10/7
 */
public class Solution54 {
    public List<Integer> spiralOrder(int[][] matrix) {
        int[][] directs = {{0, 1},{1, 0}, {0, -1}, {-1, 0}};
        int xLimit = -1;
        int yLimit = -1;
        List<Integer> result = new ArrayList<>();
        int layer = 0;
        int currentX = 0;
        int currentY = 0;
        while (result.size() < matrix.length * matrix[0].length) {
            for (int i = 0; i < 4; i++) {
                int[] direct = directs[i];
                xLimit = currentX + direct[0] * (matrix.length - 1 - layer * 2);
                yLimit = currentY + direct[1] * (matrix[0].length - 1 - layer * 2);
                if (xLimit == currentX && yLimit == currentY && i > 0) {
                    result.add(matrix[currentX][currentY]);
                    break;
                }
                while (currentX != xLimit || currentY != yLimit) {
                    result.add(matrix[currentX][currentY]);
                    currentX += direct[0];
                    currentY += direct[1];
                }
            }
            currentX += 1;
            currentY += 1;
            layer += 1;
        }
        return result;
    }

    public static void main(String[] args) {
        // int[][] matrix = new int[][]{{3},{2}};
        //int[][] matrix = new int[][]{{3},{2}};
        int[][] matrix = new int[][]{{6, 9, 7}};
        Solution54 solution54 = new Solution54();
        System.out.println(solution54.spiralOrder(matrix));
    }
}